import datetime
import os
import threading
import time

import requests
import win32gui
import cv2
import numpy as np
import pyautogui
import win32gui
from paddleocr import PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang='ch')

def get_window_geometry(title_keyword: str):
    """
    根据窗口标题关键词获取窗口的位置和大小。

    :param title_keyword: 窗口标题中的关键字（支持模糊匹配）
    :return: (left, top, width, height) 或 None 如果未找到窗口
    """

    def enum_handler(hwnd, results):
        if win32gui.IsWindowVisible(hwnd):
            title = win32gui.GetWindowText(hwnd)
            if title_keyword.lower() in title.lower():
                rect = win32gui.GetWindowRect(hwnd)
                left, top, right, bottom = rect
                width = right - left
                height = bottom - top
                results.append((left, top, width, height))

    results = []
    win32gui.EnumWindows(enum_handler, results)
    return results[0] if results else None



def find_window_position_and_check_foreground(window_title_keyword):
    def enum_handler(hwnd, result_list):
        if win32gui.IsWindowVisible(hwnd):
            title = win32gui.GetWindowText(hwnd)
            if window_title_keyword in title:
                rect = win32gui.GetWindowRect(hwnd)
                result_list.append((hwnd, title, rect))

    windows = []
    win32gui.EnumWindows(enum_handler, windows)

    if not windows:
        print(f"未找到窗口包含 '{window_title_keyword}' 的应用")
        return -1, -1, -1, -1, False
    foreground_hwnd = win32gui.GetForegroundWindow()
    for hwnd, title, rect in windows:
        x, y = rect[0], rect[1]
        width, height = rect[2] - rect[0], rect[3] - rect[1]
        is_foreground = (hwnd == foreground_hwnd)
        print(f"找到窗口: {title}")
        print(f"x={x}, y={y}, width={width}, height={height}")
        if is_foreground:
            print("该窗口当前在前台")
        else:
            print("该窗口当前不在前台")
        return x, y, width, height, is_foreground
    return -1, -1, -1, -1, False

def find_window_position(window_title_keyword):
    def enum_handler(hwnd, result_list):
        if win32gui.IsWindowVisible(hwnd):
            title = win32gui.GetWindowText(hwnd)
            if window_title_keyword in title:
                rect = win32gui.GetWindowRect(hwnd)
                result_list.append((title, rect))

    windows = []
    win32gui.EnumWindows(enum_handler, windows)

    if not windows:
        print(f"未找到窗口包含 '{window_title_keyword}' 的应用")
        return -1,-1,-1,-1
    else:
        flag = False
        x,y,width,height = -1,-1,-1,-1
        # 获取当前活动窗口
        foreground_hwnd = win32gui.GetForegroundWindow()
        print(foreground_hwnd)
        for hwnd in windows:
            print(hwnd)
            if hwnd == foreground_hwnd:
                print(f"窗口 '{win32gui.GetWindowText(hwnd)}' 当前在前台")
                flag = True
                break
        if not flag:
            print(f"窗口包含 '{window_title_keyword}' 的应用不在前台")
        else:
            for title, rect in windows:
                x, y = rect[0], rect[1]
                width, height = rect[2] - rect[0], rect[3] - rect[1]
                print(f"找到窗口: {title}")
                print(f"x={x}, y={y}, width={width}, height={height}")
        return int(x),int(y),int(width),int(height)

def screenshot(x,y,width,height,filename):
    print(f"<截图>{x},{y},{width},{height}")
    screen = pyautogui.screenshot(region=(x, y, width, height))
    screen.save(filename+".png")


def getTextPosition(text,x,y,width,height,filename):
    time.sleep(0.2)
    # 截取指定区域的屏幕
    screen = pyautogui.screenshot(region=(x, y, width, height))
    img_np = np.array(screen)
    image = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
    # 使用 OCR 识别文本
    result = ocr.ocr(image, cls=True)
    # 遍历识别结果
    if result is not None:
        for line in result[0]:
            detected_text = line[1][0]  # 获取识别出的文本
            coordinates = line[0]  # 获取文本的坐标信息
            x1, y1 = coordinates[0]
            x3, y3 = coordinates[2]
            # 计算矩形框的 width 和 height
            width = x3 - x1
            height = y3 - y1
            # 如果识别的文本包含目标文本
            if text in detected_text:
                print(f"找到目标文本 '{text}'，坐标: ({x1}, {y1}), 宽度: {width}, 高度: {height}")
                return int(x1), int(y1), int(width), int(height), True  # 返回矩形框的 x, y, width, height
        # 如果没有找到目标文本，返回 -1
        print(f"未找到目标文本 '{text}'。")
        return -1, -1, -1, -1, False
    else:
        return -1, -1, -1, -1, False

def click(x,y):
    print(f"点击位置：{x,y}")
    pyautogui.moveTo(x, y)
    pyautogui.click(x,y)

def scroll(height):
    pyautogui.scroll(height)
    pyautogui.scroll(20)

def getWalletPosition(walletText, windowX, windowY, windowWidth, windowHeight):
    return getTextPosition(walletText, windowX, windowY, windowWidth, windowHeight,'0')

def getWalletInfo(windowX, windowY, windowWidth, windowHeight):
    centerX = windowX+int(windowWidth/2)
    centerY = windowY+int(windowHeight/2)
    walletHalfWidth = 240
    walletHalfHeight = 360
    return centerX-walletHalfWidth,centerY-walletHalfHeight,walletHalfWidth*2,walletHalfHeight*2

from skimage.metrics import structural_similarity as compare_ssim
def is_similar(img1_path, img2_path, similarity_threshold=0.95):
    img1 = cv2.imread(img1_path)
    img2 = cv2.imread(img2_path)
    print(img1_path)
    print(img2_path)
    # 转灰度图（SSIM要求灰度）
    img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

    # 计算结构相似度（返回值范围 [-1, 1]，越接近1越相似）
    score, _ = compare_ssim(img1_gray, img2_gray, full=True)

    print(f"相似度得分：{score}")

    return score >= similarity_threshold



def saveWalletList(walletLeft,walletTop,walletWidth,walletHeight,folder,filename):
    # 截图第一张
    base_dir = r"d:\redpackage"
    save_dir = os.path.join(base_dir, folder)
    os.makedirs(save_dir, exist_ok=True)
    img = pyautogui.screenshot(
        region=(walletLeft,walletTop,walletWidth,walletHeight))
    img_path = os.path.join(save_dir, f"{filename}.png")
    img.save(img_path)
    return img_path


def scrollWalletHeight(i):
    walletUserInfoHeight = 30
    if i == 2:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll(40 * -1)
    elif i == 3:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll(74 * -1)
    elif i == 4:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll(72 * -1)



    elif i == 5:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
    elif i == 6:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
    elif i == 7:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
    elif i == 8:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
    elif i == 9:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
    elif i == 10:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
    elif i == 11:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
    elif i == 12:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
    elif i == 13:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)
    else:
        pyautogui.scroll((2 * walletUserInfoHeight + 45) * -1)

def send_request(batchId):
    try:
        url = f"http://localhost:8887/api/send?batchId={batchId}"
        print(f"请求URL: {url}")
        response = requests.get(url)
        print(f"响应状态码: {response.status_code}")
        print(f"响应内容: {response.text}")
    except Exception as e:
        print(f"请求失败: {e}")

def close(x,y,folder,windowHeight):
    pyautogui.moveTo(x,y)
    pyautogui.click(x,y)
    print("关闭了")
    pyautogui.sleep(0.3)
    pyautogui.scroll(-1 * int(windowHeight / 1.5))
    pyautogui.scroll(10)
    # 开启后台线程执行请求
    send_request(folder)


def rob():
    """
    抢红包
    :return:
    """
    click(windowX + windowInfo[0], windowY + windowInfo[1])
    close(walletInfo[0] + walletInfo[2] - 30, walletInfo[1] + 8, "-1", windowHeight)
    time.sleep(0.2)
    pyautogui.scroll(-800)